package controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.Domain;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;


@SuppressWarnings("serial")
public class SameDomainServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		
		String path = ((HttpServletRequest)req).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	
        	resp.getWriter().println("Bad request : "+req.getRequestURI());
        	resp.getWriter().close();
        	return ;
        	
        }
		st.nextToken();
		String name = Utils.fomatDomain(st.nextToken());
		if(Utils.checkDomain(name))
		{
			try {
				ObjectifyService.register(Domain.class);
			} catch (Exception e) {
				// TODO: handle exception
			}
			Objectify objectify = ObjectifyService.begin();
			try {
				Query<Domain> list = objectify.query(Domain.class).filter("sdDomain", name).limit(20);
	
				resp.setHeader( "Cache-Control", "public, max-age=86400");
				resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
				
				req.setAttribute("list", list);
				req.setAttribute("ip", name);
				try {
					req.getRequestDispatcher("/same_domain.jsp").forward(req, resp);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} catch (Exception e) {
				try {
					req.getRequestDispatcher("/404error.jsp").forward(req, resp);
				} catch (Exception e1) {
					e.printStackTrace();
				}
	        	return;
			}
		} else {
			resp.sendRedirect("/gsearch?cx=012442764171928889326:_zsyjyuyyuu&cof=FORID%3A10&ie=UTF-8&q="+name+"&sa=Search");
		}
	}

}
